<!--
 - Author : wang885298.
 - Date   : 2018/6/14.
 - File   : release.发布
 -->

<template>
  <div class="rel">
    <mt-header :title="title" fixed>
      <router-link to="/" slot="left">
        <mt-button icon="back"></mt-button>
      </router-link>
      <mt-button slot="right" @click="release()">发布</mt-button>
    </mt-header>
    <div class="re-content">
      <input class="userName" type="text" v-model="userName">
      <textarea name="" id="" cols="25" rows="10" placeholder="描述...(严禁发布违反国家法律法规言论，如反动，色情，迷信，暴力等）"
          v-model="content"></textarea>
      <div class="upload">
        <div class="upload-item" v-for="(item, index) in fileList" :key="index">
          <div class="close">
            <img src="../assets/images/close.png" alt="" @click="close(index)">
          </div>
          <img :src="item" alt="" v-if="fileType==='image'">
          <video :src="item" v-if="fileType==='video'" loop autoplay muted @click="close(index)"></video>
        </div>
        <div class="upload-item" style="background-color: #fff" v-show="addShow" @click="actionSheet">
          <img src="../assets/images/00.png" alt="">
          <input class="file" type="file" accept="image/*" id="imgUpload" @change="upload($event)" multiple>
          <input class="file" type="file" accept="image/*" id="imgSingleUpload" @change="upload($event)">
          <input class="file" type="file" accept="video/*" id="videoUpload" @change="upload($event)">
        </div>
      </div>
    </div>

    <mt-actionsheet
        :actions="data"
        v-model="sheetVisible">
    </mt-actionsheet>
  </div>
</template>

<script>
  import { Indicator, MessageBox } from 'mint-ui'
  import lrz from 'lrz'
  export default {
    data () {
      return {
        title: '发布文明点赞',
        patType: this.$route.query.patType,
        fileList: [], // 本地预览的文件列表
        fileType: '', // 文件类型
        fileTypes: '', // 文件类型
        addShow: true, // 显示添加图片按钮
        userName: '游客',
        content: '',
        fileArr: [], // 要上传的文件列表
        sheetVisible: false,
        Nv: navigator.userAgent.toLowerCase().indexOf('oneplus a5010') ===-1,
        data: [{
          name: '手机图片',
          method: () => {
            this.sheetVisible = false
            this.fileTypes = 1
            console.log('Nv', this.Nv, navigator.userAgent.toLowerCase().indexOf('oneplus a5010'))
            if (this.Nv) {
              document.getElementById('imgUpload').click()
            } else {
              document.getElementById('imgSingleUpload').click()
            }
          }
        }, {
          name: '视频',
          method: () => {
            this.sheetVisible = false
            this.fileTypes = 2
            document.getElementById('videoUpload').click()
          }
        }]
      }
    },
    mounted () {
      if (this.patType === 1) {
        this.title = '发布文明点赞'
      } else {
        this.title = '发布不文明曝光'
      }
    },
    methods: {
      /**
       * 发布随手拍
       */
      release () {
        if (!this.content.trim().length || !this.userName.trim().length || !this.fileArr.length) {
          if (!this.content.trim().length) {
            this.$toast('随手拍内容不能为空！')
            return
          }
          if (!this.userName.trim().length) {
            this.$toast('随手拍发布者姓名不能为空！')
            return
          }
          if (!this.fileArr.length) {
            this.$toast('图片或视频不能为空！')
            return
          }
        } else {
          Indicator.open({
            text: '提交中...',
            spinnerType: 'fading-circle'
          })
          let formFile = new FormData()
          formFile.append("content", this.content) // 加入内容
          formFile.append("userName", this.userName) // 加入姓名
          formFile.append("fileType", this.fileTypes) // 文件类型
          formFile.append("type", this.patType) // 文明标识
          for (let i = 0; i < this.fileArr.length; i++) {
            formFile.append("multipartFile", this.fileArr[i], this.fileArr[i].fileName) // 文件数组
          }
          this.$request.addSnapShot(formFile).then((response) => {
            Indicator.close()
            MessageBox({
              title: '提示',
              message: '已提交成功，请耐心等待后台管理员对您的内容审核，审核通过后即可在页面查看。',
              closeOnClickModal: false,
              confirmButtonText: '确定',
              confirmButtonClass: 'confirmBtnCls'
            }).then(action => {
              if (action === 'confirm') {
                this.userName = '游客'
                this.content = ''
                this.fileList = []
                this.fileArr = []
                this.addShow = true
                this.$router.push({
                  path: '/',
                  query: {current: (this.patType - 1)}
                })
              }
            })
          }).catch(e => {
            console.error(e)
            MessageBox('提示', '发布失败！')
          })
        }
      },
      /**
       * 显示上传图片格式
       */
      actionSheet () {
        if (this.fileType === 'image') {
          if (this.Nv) {
            document.getElementById('imgUpload').click()
          } else {
            document.getElementById('imgSingleUpload').click()
          }
        } else {
          this.sheetVisible = true
        }
      },
      /**
       * 图片上传
       */
      upload (e) {
        let tmpL = this.fileArr.length
        let files = e.target.files
        console.log('文件', files)
        let len = tmpL + files.length //选择的文件总数
        if (len > 9) {
          this.$toast('最多只能上传9张图片')
          return
        }
        if (!files[0].type) {
          return
        }
        this.fileType = files[0].type.split('/')[0]
        if (this.fileType !== 'image') {
          //上传视频时的操作
          Indicator.open({
            text: '文件上传中...',
            spinnerType: 'fading-circle'
          })
          this.addShow = false
          for (let i = 0; i < files.length; i++) {
            let reader = new FileReader()
            reader.readAsDataURL(files[i])
            this.fileArr.push(files[i])
            if (this.fileArr[i].size > 52428800) {
              MessageBox({
                title: '提示',
                message: '文件大于50M,请选择重新选择！',
                closeOnClickModal: false,
                confirmButtonText: '确定',
                confirmButtonClass: 'confirmBtnCls'
              }).then(action => {
                if (action === 'confirm') {
                  this.fileArr = []
                  this.addShow = true
                  Indicator.close()
                  document.getElementById('videoUpload').value = ''
                }
              })
              return
            }
            reader.onload = (e) => {
              this.fileList.push(e.target.result)
              if (this.fileList.length > 0) {
                Indicator.close()
              }
            }
            document.getElementById('videoUpload').value = ''
          }
        } else {
          Indicator.open({
            text: '文件上传中...',
            spinnerType: 'fading-circle'
          })
          //传的是图片时进行图片压缩
          for (let i = 0; i < files.length; i++) {
            lrz(files[i]).then((rst) => {
              let compressFile = rst.file
              compressFile.fileName = rst.origin.name
              this.fileArr.push(compressFile)
              this.fileList.push(rst.base64)
              if (i === (files.length - 1)) {
                Indicator.close()
                if (this.Nv) {
                  document.getElementById('imgUpload').value = ''
                } else {
                  document.getElementById('imgSingleUpload').value = ''
                }
              }
            })
          }
        }
      },
      /**
       * 删除本地预览图片
       */
      close (index) {
        this.fileList.splice(index, 1)
        this.fileArr.splice(index, 1)
        if (!this.fileList.length) {
          this.fileType = ''
          this.addShow = true
        }
      }
    }
  }
</script>

<style lang="less" rel="stylesheet/less">
  @import "../assets/less/color.less";
  @import "../assets/less/fontSize.less";

  .mint-header {
    background-color: #52d8e4 !important;
    color: #fff!important;
    box-shadow: 1px 2px 4px #eee!important;
    font-size: @bigSize!important;
  }

  .rel {
    height: 100%;
    overflow: auto;
  }

  .re-content {
    overflow: hidden;
    padding-top: 40px;
    background-color: #fff;
    textarea {
      width: 100%;
      border: none;
      padding: 20px 10px;
      font-size: @mainTxtSize;
    }
    .upload {
      display: flex;
      flex-wrap: wrap;
      padding: 10px;
      &-item {
        width: 30%;
        max-width: 10rem;
        position: relative;
        margin: 10px 1.5%;
        height: 10rem;
        display: flex;
        overflow: hidden;
        background-color: black;
        img, video {
          width: 100%;
          align-self: center;
        }
        .file {
          position: absolute;
          width: 0;
          height: 0;
          opacity: 0;
        }
        .close {
          position: absolute;
          right: 0;
          top: 0;
          width: 2rem;
          height: 2rem;
          img {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
    .userName {
      width: 101%;
      border-top: 10px solid #eee;
      border-bottom: 10px solid #eee;
      padding: 10px 10px;
      margin-left: -2px;
      font-size: 1.6rem;
    }
  }
</style>
